import { useState, useEffect, useRef } from 'react';
import { cn } from '@/lib/utils';

interface SearchBarProps {
  query: string;
  onChange: (query: string) => void;
  results: any[];
  showResults: boolean;
  onRoleSelect: (role: any) => void;
}

export default function SearchBar({ query, onChange, results, showResults, onRoleSelect }: SearchBarProps) {
  const [isFocused, setIsFocused] = useState(false);
  const searchRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (searchRef.current && !searchRef.current.contains(event.target as Node)) {
        setIsFocused(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);

  return (
    <div ref={searchRef} className="relative">
      <div className="relative">
        <input
          type="text"
          value={query}
          onChange={(e) => onChange(e.target.value)}
          onFocus={() => setIsFocused(true)}
          placeholder="搜索角色..."
          className="w-full py-4 px-5 pr-12 rounded-2xl border border-gray-200 shadow-lg focus:outline-none focus:ring-2 focus:ring-blue-500 transition-all"
        />
        <button className="absolute right-4 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-blue-600 transition-colors">
          <i className="fa-solid fa-search text-xl"></i>
        </button>
      </div>

      {(showResults && isFocused && results.length > 0) && (
        <div className="absolute mt-2 w-full bg-white rounded-xl shadow-xl border border-gray-100 overflow-hidden z-10 animate-in fade-in slide-in-from-top-5 duration-200">
          {results.map((role) => (
            <div 
              key={role.id}
              onClick={() => onRoleSelect(role)}
              className="p-4 hover:bg-blue-50 transition-colors cursor-pointer border-b border-gray-100 last:border-0"
            >
              <h3 className="font-semibold text-blue-800">{role.name}</h3>
              <p className="text-sm text-gray-600 line-clamp-1">{role.description}</p>
            </div>
          ))}
        </div>
      )}

      {(showResults && isFocused && results.length === 0 && query.length > 0) && (
        <div className="absolute mt-2 w-full bg-white rounded-xl shadow-xl border border-gray-100 p-6 z-10 animate-in fade-in slide-in-from-top-5 duration-200">
          <p className="text-center text-gray-500">未找到匹配的角色</p>
        </div>
      )}
    </div>
  );
}